package com.magupe.push.server.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.magupe.push.common.protocol.request.AuthenticationRequestPacket;
import com.magupe.push.common.protocol.response.AuthenticationResponsePacket;
import com.magupe.push.common.session.AuthenticationSession;
import com.magupe.push.log.util.LogUtils;
import com.magupe.push.server.utils.AuthenticationSessionUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 后端认证，该后端认证成功之后，可以推送消息给客户端（即移动端）
 */
public class AuthenticationRequestHandler extends SimpleChannelInboundHandler<AuthenticationRequestPacket> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, AuthenticationRequestPacket packet) throws Exception {
		AuthenticationResponsePacket authenticationResponsePacket = new AuthenticationResponsePacket();
		authenticationResponsePacket.setVersion(packet.getVersion());
		authenticationResponsePacket.setSource(packet.getSource());
		authenticationResponsePacket.setMsgId(packet.getMsgId());
		authenticationResponsePacket.setSuccess(true);
		authenticationResponsePacket.setSecret(packet.getSecret());
		authenticationResponsePacket.setContentId(packet.getContentId());
		
		String contentId = packet.getContentId();
		String secret = packet.getSecret();
		
        if (valid(ctx, secret, contentId)) {
        	LogUtils.processLog(ctx.channel(), packet, "客户端认证成功", false, null);

        	AuthenticationSessionUtil.bindAuthenticationSession(new AuthenticationSession(secret, contentId), ctx.channel());
        	
        	ctx.channel().writeAndFlush(authenticationResponsePacket);		
        } else {
        	LogUtils.processLog(ctx.channel(), packet, "客户端认证失败", false, null);
        	
        	authenticationResponsePacket.setSuccess(false);
        	ctx.channel().writeAndFlush(authenticationResponsePacket);	
        	ctx.close();
        }
	}

	/**
	 * 读取secret和contentId在信息库中，看是否存在，该操作应当异步进行
	 * @param secret
	 * @param contentId
	 * @return
	 */
	private boolean valid(ChannelHandlerContext ctx, String secret, String contentId) {
		InputStream is = AuthenticationRequestHandler.class.getClassLoader().getResourceAsStream("data.txt");
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String str;
		try {
			str = br.readLine();
			JSONObject jsonObject = JSONObject.parseObject(str);
			JSONArray array = jsonObject.getJSONArray("list");
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = array.getJSONObject(i);
				map.put(object.getString("contentId"), object.getString("secret"));
			}
			if(map.get(contentId).equals(secret)) {
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
			LogUtils.processExceptionLog(ctx, e, "Authentication Valid");
		} finally {
			try {
				br.close();
				isr.close();
				is.close();
			} catch (IOException e) {e.printStackTrace();LogUtils.processExceptionLog(ctx, e, "Stream Close");}
		}

		return false;
	}

}
